from flask import current_app
from flask import g, jsonify
from flask import redirect,request
from flask import render_template
from flask import session

from info import constants
from info import db
from info.models import News, Category
from info.utils.common import user_login_data
from info.utils.qiniu_storage import storage
from info.utils.response_code import RET
from . import profile_blu


@profile_blu.route("/info")
@user_login_data
def user_info():
    user = g.user
    if not user:
        # 用户未登录，重定向到主页
        return redirect('/')
    # 添加测试数据
    # try:
    #     for i in range(100, 250):
    #         user.collection_news.append(News.query.get(i))
    #     db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)
    #     db.session.rollback()
    #     return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    data = {
        "user": user.to_dict() if user else None,
    }
    return render_template("news/user.html", data=data)


@profile_blu.route("/base_info",methods=["POST","GET"])
@user_login_data
def base_info():
    user = g.user
    if not user:
        return render_template("/")
    if request.method == "GET":
        data = {
            "user":user.to_dict() if user else None
        }
        return render_template("news/user_base_info.html", data=data)

    data_dict = request.json
    signature = data_dict.get("signature")
    nick_name = data_dict.get("nick_name")
    gender = data_dict.get("gender")
    if not all([nick_name,gender,signature]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="数据库操作失败")
    session["nick_name"] = nick_name
    return jsonify(errno=RET.OK,errmsg="操作成功")


@profile_blu.route("/pic_info",methods=["POST","GET"])
@user_login_data
def pic_info():
    user = g.user
    if not user:
        return render_template("/")
    if request.method == "GET":
        data = {
            "user":user.to_dict() if user else None
        }
        return render_template("news/user_pic_info.html", data=data)

    # 1.1, 获取参数，参数就是上传来的图片 读取 .read()
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    # 2.上传图片到七牛云
    try:
        avatar_url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="图片上传失败")
    # 3.保存图片路径到 user的avatar_url字段
    user.avatar_url = avatar_url
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="数据库操作失败")
    # 4.返回成功, 同时返回路径给ajax的回调函数
    return jsonify(errno=RET.OK,errmsg="操作成功",data={"avatar_url":constants.QINIU_DOMIN_PREFIX + avatar_url})


@profile_blu.route("/pass_info",methods=["POST","GET"])
@user_login_data
def pass_info():
    user = g.user
    if not user:
        return render_template("/")
    if request.method == "GET":
        data = {
            "user":user.to_dict() if user else None
        }
        return render_template("news/user_pass_info.html", data=data)
    # 1.获取参数
    data_dict = request.json
    old_password = data_dict.get("old_password")
    new_password = data_dict.get("new_password")
    new_password2 = data_dict.get("new_password2")
    # 2.判空、校验
    if not all([old_password,new_password,new_password2]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    if new_password != new_password2:
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PARAMERR, errmsg="密码错误")
    # 3.修改密码到数据库
    try:
        user.password = new_password
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    # 4.返回成功操作
    return jsonify(errno=RET.OK, errmsg="修改成功")


@profile_blu.route("/collection")
@user_login_data
def collection():
    user = g.user
    if not user:
        return render_template("/")

    # 1.获取参数,校验
    p= request.args.get("p",1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 2, 分页查询
    try:
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS)
        cur_page_news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
    # 把对象列表，转成字典列表
    cur_page_news_list = []
    for i in cur_page_news:
        cur_page_news_list.append(i.to_dict())
    # 3, 返回成功  ？
    data = {"cur_page_news_list": cur_page_news_list,
            "current_page":current_page,
            "total_page": total_page}
    return render_template("news/user_collection.html", data=data)


@profile_blu.route("/news_list")
@user_login_data
def news_list():
    user = g.user
    if not user:
        return render_template("/")

    # 1.获取参数,校验
    p= request.args.get("p",1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 2, 分页查询
    try:
        paginate = user.news_list.paginate(p, constants.USER_COLLECTION_MAX_NEWS)
        cur_page_news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
    # 把对象列表，转成字典列表
    cur_page_news_list = []
    for i in cur_page_news:
        cur_page_news_list.append(i.to_review_dict())
    # 3, 返回成功  ？
    data = {"cur_page_news_list": cur_page_news_list,
            "current_page":current_page,
            "total_page": total_page}
    return render_template("news/user_news_list.html", data=data)


@profile_blu.route("/news_release",methods=["POST","GET"])
@user_login_data
def news_release():
    user = g.user
    if not user:
        return render_template("/")
    if request.method == "GET":
        categories = Category.query.all()
        data = {
            "user":user.to_dict() if user else None,
            "categories":categories
        }
        return render_template("news/user_news_release.html", data=data)
    # 1.获取参数
    data_dict = request.form
    title = data_dict.get("title")
    category_id = data_dict.get("category_id")
    digest = data_dict.get("digest")
    content = data_dict.get("content")
    index_image = request.files.get("index_image")
    source = "个人发布"
    # 2.判空
    if not all([title,category_id,digest,content,index_image]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    # 3.上传图片到七牛云
    try:
        index_file = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    try:
        index_image_url = storage(index_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="上传图片错误")
    # 4.创建News对象保存数据库
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + index_image_url
    news.source = source
    news.user_id = user.id
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    # 5.返回成功
    return jsonify(errno=RET.OK, errmsg="发布成功")